<template>
  <div class="userInfo">
    <div class="plus"></div>
    <van-nav-bar title="个人资料" left-text="返回" left-arrow @click-left="goBack" />
    <div class="bg"></div>
    <div class="content">
      <ul class="box">
        <li class="img">
          <span>头像</span>
          <van-uploader :after-read="changeImg">
            <img :src="userInfo.userImg" alt="">
          </van-uploader>
        </li>
        <li>
          <span>用户id</span>
          <p>{{userInfo.userId}}</p>
        </li>
        <li>
          <span>昵称</span>
          <van-field v-model="nickName" @blur="changeNickName" input-align="right" @click="changeCursor" ref="nickName" />
        </li>
        <li>
          <span>简介</span>
          <van-field v-model="desc" @blur="changeDesc" input-align="right" @click="changeCursor" ref="desc" />
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: "UserInfo",

  data() {
    return {
      userInfo: [],
      nickName: '',
      desc: '',
      inputActive: false
    };
  },

  created() {
    // 获取用户信息
    this.getUserInfo();
  },

  methods: {
    goBack() {
      this.$router.replace({name: 'User'});
    },

    // 获取用户信息
    getUserInfo() {
      let tokenString = this.$cookies.get("TOKEN");
      this.axios
        .get("findAccountInfo", {
          params: {
            tokenString,
          },
        })
        .then((res) => {
          // 
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === "B001") {
            this.userInfo = res.data.result[0];
            // 昵称
            this.nickName = res.data.result[0].nickName;
            // 简介
            this.desc = res.data.result[0].desc;
          }
        })
        .catch((err) => {
          
        });
    },

    // 修改头像
    changeImg(file) {
      // 此时可以自行将文件上传至服务器
      // 
      let tokenString = this.$cookies.get("TOKEN");
      let imgType = file.file.name.split('.')[1];
      // 
      let serverBase64Img = file.content.replace(/^data:image\/[A-Za-z]+;base64,/, '');
      // 
      this.axios
        .post("updateAvatar", {
            tokenString,
            imgType,
            serverBase64Img
        })
        .then((res) => {
          
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === "H001") {
            this.$toast(res.data.msg);
            // 延迟1秒后更新页面数据
            let timer = setTimeout(() => {
              clearTimeout(timer);
              // 调用查询用户信息方法更新页面数据
              this.getUserInfo();
            }, 1000);
          }
        })
        .catch((err) => {
          
        });
    },

    // 修改昵称
    changeNickName() {
      // 将输入框状态设置为初始状态
      this.inputActive = false;
      
      let nickName = this.nickName;
      if(nickName == this.userInfo.nickName) return;
      if(!nickName) return;
      let tokenString = this.$cookies.get("TOKEN");
      this.axios
        .post("updateNickName", {
            tokenString,
            nickName
        })
        .then((res) => {
          // 
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === "C001") {
            this.$toast(res.data.msg);
            // 延迟2秒后更新页面数据
            let timer = setTimeout(() => {
              clearTimeout(timer);
              // 调用查询用户信息方法更新页面数据
              this.getUserInfo();
            }, 2000);
          }
        })
        .catch((err) => {
          
        });
    },

    // 修改简介
    changeDesc() {
      // 将输入框状态设置为初始状态
      this.inputActive = false;

      let desc = this.desc;
      if(desc == this.userInfo.desc) return;
      if(!desc) return;
      let tokenString = this.$cookies.get("TOKEN");
      this.axios
        .post("updateDesc", {
            tokenString,
            desc
        })
        .then((res) => {
          // 
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === "D001") {
            this.$toast(res.data.msg);
            // 延迟1秒后更新页面数据
            let timer = setTimeout(() => {
              clearTimeout(timer);
              // 调用查询用户信息方法更新页面数据
              this.getUserInfo();
            }, 1000);
          }
        })
        .catch((err) => {
          
        });
    },

    // 修改光标位置
    changeCursor() {
      // 取消事件默认行为
      event.preventDefault();
      // 获取事件源
      let tag = event.target;
      // 如果输入框状态为假，表示第一次点击（并未获取光标），将光标定位至末尾
      if(!this.inputActive) {
        // 改变输入框状态（除第一次点击之外的事件不能触发修改光标位置）
        this.inputActive = true;
        tag.selectionStart = tag.value.length;
        tag.selectionEnd = tag.value.length;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.van-nav-bar {
  /deep/.van-icon {
    color: #ffa341;
  }
  /deep/.van-nav-bar__text {
    color: #ffa341;
  }
  /deep/.van-nav-bar__title {
    color: #333;
  }
}

.userInfo {
  .bg {
    width: 100%;
    height: 100px;
    background: #ff594d;
  }
  .content {
    margin-top: -30px;
    padding: 10px;
    color: #333;
    font-size: 14px;
    box-sizing: border-box;
    .box {
      padding: 0 10px;
      background: #fff;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      li {
        display: flex;
        align-items: center;
        line-height: 50px;
        border-bottom: 1px solid #eee;
        &:last-child {
          border-bottom: none;
        }
      }
      span {
        margin-right: auto;
      }
      p {
        margin: 0;
        color: #999;
      }
      .img {
        
        img {
          display: flex;
          width: 35px;
          height: 35px;
          border-radius: 50%;
        }
      }
      /deep/ .van-cell {
        flex: 1;
        padding: 0;
        width: auto;
      }
      /deep/ .van-field__control {
        color: #999;
      }
    }
  }
}
</style>